;; solutions to Guided Practice 6.1: pizza problem (define-struct topped-pizza (topping base)) ;; A Topping is a String. ;; A Pizza is either ;; -- the string "plain crust" ;; -- (make-topped-pizza Topping Pizza) ;; INTERP: ;; "plain crust" means a pizza with no toppings ;; (make-topped-pizza t p) represents the pizza p with topping t added ;; on top. ;; empty-pizza? : Pizza -> Boolean ;; RETURNS: true iff the pizza is empty ;; STRATEGY: function composition ;; Note: string=? only works on strings, so we need to _guard_ call the ;; string-equal? with a string? test. (define (empty-pizza? p) (if (string? p) (string-equal? p "plain crust") false)) ;; replace-all-anchovies-with-onions ;; : Pizza -> Pizza ;; RETURNS: a pizza like the given pizza, but with ;; anchovies in place of each layer of onions ;; STRATEGY: Structural decomposition on p : Pizza (define (replace-all-anchovies-with-onions p) (cond [(empty-pizza? p) empty] [else (if (string=? (topped-pizza-topping p) "anchovies") (make-topped-pizza "onions" (replace-all-anchovies-with-onions (topped-pizza-base p))) (make-topped-pizza (topped-pizza-topping p) (replace-all-anchovies-with-onions (topped-pizza-base p))))])) ;; replace-all-anchovies : Pizza Topping -> Pizza ;; RETURNS: a pizza like the given pizza, but with ;; all anchovies replaced by the given topping. ;; STRATEGY: Structural decomposition on p : Pizza (define (replace-all-anchovies p replacement) (cond [(empty-pizza? p) empty] [else (if (string=? (topped-pizza-topping p) "anchovies") (make-topped-pizza replacement (replace-all-anchovies (topped-pizza-base p) replacement)) (make-topped-pizza (topped-pizza-topping p) (replace-all-anchovies (topped-pizza-base p) replacement)))])) ;; replace-topping : Pizza Topping Topping -> Pizza ;; RETURNS: a pizza like the given one, but with ;; all instances of the first topping replaced by ;; the second one. ;; STRATEGY: Structural decomposition on p : Pizza (define (replace-topping p topping replacement) (cond [(empty-pizza? p) empty] [else (if (string=? (topped-pizza-topping p) topping) (make-topped-pizza replacement (replace-topping (topped-pizza-base p) topping replacement)) (make-topped-pizza (topped-pizza-topping p) (replace-topping (topped-pizza-base p) topping replacement)))]))